{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python基础：列表、元组、词典"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 一、列表 [] list\n",
    "### 列表是Python中的一种数据结构，它可以存储不同类型的数据\n",
    "- 列表索引是从0开始的，我们可以通过下标索引的方式来访问列表中的值。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[13, 12.4, 'china', 'China', [1, 2, 3]]\n"
     ]
    }
   ],
   "source": [
    "A = [13, 12.4,'china',\"China\",[1,2,3]]\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "# 访问列表  A[index]  # index 索引号是从0开始编号\n",
    "A = [1, 'xiaoWang', 'a', [2, 'b'], 15.2]\n",
    "print(A[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xiaoWang\n",
      "a\n",
      "[2, 'b']\n"
     ]
    }
   ],
   "source": [
    "print(A[1])\n",
    "print(A[2])\n",
    "print(A[3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "b\n"
     ]
    }
   ],
   "source": [
    "print(A[3][0])\n",
    "print(A[3][1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15.2\n"
     ]
    }
   ],
   "source": [
    "print(A[4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'hello'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = 'helloworld'\n",
    "x[0:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 'xiaoWang', 'a']\n"
     ]
    }
   ],
   "source": [
    "print(A[0:3])  # 包含index0，不包含index3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "15.2"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A[-1]  # 倒数第一个"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 'xiaoWang', 'a', [2, 'b']]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A[:-1]   # 从第一个到 倒数第二个"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. 列表的循环遍历"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n"
     ]
    }
   ],
   "source": [
    "# 1. 使用for循环遍历列表\n",
    "namesList = ['xiaoWang','xiaoZhang','xiaoHua']\n",
    "for i in namesList:\n",
    "    print(i)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "# 2. 使用while循环遍历列表\n",
    "namesList = ['xiaoWang','xiaoZhang','xiaoHua','xiaoMing']\n",
    "length = len(namesList)  # len（） 获取list的长度：里面有多个元素\n",
    "print(length)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n",
      "xiaoMing\n"
     ]
    }
   ],
   "source": [
    "i = 0\n",
    "while i<length:\n",
    "    print(namesList[i])\n",
    "    i+=1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 列表的常见操作"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### （1）在列表中增加元素\n",
    "- 通过**append**可以向列表添加元素\n",
    "- 通过**extend**可以将另一个列表的元素添加到列表中。\n",
    "- 通过**insert**在指定位置index前插入元素object。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----添加之前，列表A的数据-----\n",
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n"
     ]
    }
   ],
   "source": [
    "# 通过append可以向列表添加元素\n",
    "A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "print(\"-----添加之前，列表A的数据-----\")\n",
    "for tempName in A:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入要添加的学生姓名:张三\n",
      "\n",
      "-----添加之后，列表A的数据-----\n",
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n",
      "张三\n"
     ]
    }
   ],
   "source": [
    "# 提示并添加元素\n",
    "temp = input('请输入要添加的学生姓名:')\n",
    "A.append(temp) # append函数向list尾部添加新的元素\n",
    "\n",
    "print()\n",
    "print(\"-----添加之后，列表A的数据-----\")\n",
    "for tempName in A:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A.append(B): ['xiaoWang', 'xiaoZhang', 'xiaoHua', ['zhao1', 'zhao2']]\n"
     ]
    }
   ],
   "source": [
    "A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "B = ['zhao1','zhao2']\n",
    "A.append(B)         # B还是会以list的方式添加到A的尾部\n",
    "print(\"A.append(B):\",A )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A.extend(B): ['xiaoWang', 'xiaoZhang', 'xiaoHua', 'zhao1', 'zhao2']\n"
     ]
    }
   ],
   "source": [
    "# 通过extend可以将另一个列表的元素添加到列表中\n",
    "A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "B = ['zhao1','zhao2']\n",
    "A.extend(B)     # B的元素会添加到A的尾部，不是以子列表的形式。\n",
    "print(\"A.extend(B):\", A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['xiaoWang', ['zhao1', 'zhao2'], 'xiaoZhang', 'xiaoHua']\n"
     ]
    }
   ],
   "source": [
    "# insert 指定的索引位置增加元素\n",
    "A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']\n",
    "B = ['zhao1','zhao2']\n",
    "A.insert(1, B)\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### （2）在列表中查找元素\n",
    "- **in（存在）**,如果存在那么结果为True，否则为False。\n",
    "- **not in（不存在）**，如果不存在那么结果为True，否则False。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入要查找的姓名:xiaoWang\n",
      "在列表中找到了相同的名字\n"
     ]
    }
   ],
   "source": [
    "#待查找的列表\n",
    "nameList = ['xiaoWang','xiaoZhang','xiaoHua']\n",
    "\n",
    "#获取用户要查找的名字\n",
    "findName = input('请输入要查找的姓名:')\n",
    "\n",
    "#查找是否存在\n",
    "if findName in nameList:\n",
    "    print('在列表中找到了相同的名字')\n",
    "else:\n",
    "    print('没有找到')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### （3）在列表中修改元素\n",
    "- 通过**下标**来实现的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----修改之前，列表A的数据-----\n",
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoHua\n"
     ]
    }
   ],
   "source": [
    "#定义变量A，默认有3个元素\n",
    "A = ['xiaoWang','xiaoZhang','xiaoHua']\n",
    "print(\"-----修改之前，列表A的数据-----\")\n",
    "for tempName in A:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----修改之后，列表A的数据-----\n",
      "xiaoWang\n",
      "xiaoZhang\n",
      "xiaoLu\n"
     ]
    }
   ],
   "source": [
    "#修改元素\n",
    "A[2] = 'xiaoLu'\n",
    "print(\"-----修改之后，列表A的数据-----\")\n",
    "for tempName in A:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### （4）在列表中删除元素\n",
    "- **del**：根据下标进行删除，del A[1]\n",
    "- **pop**：删除最后一个元素，A.pop()\n",
    "- **remove**：根据元素的值进行删除，"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------删除之前------\n",
      "加勒比海盗\n",
      "骇客帝国\n",
      "第一滴血\n",
      "指环王\n",
      "霍比特人\n",
      "速度与激情\n"
     ]
    }
   ],
   "source": [
    "# 使用del方法删除列表中的元素\n",
    "movieName = ['加勒比海盗', '骇客帝国', '第一滴血', '指环王', '霍比特人', '速度与激情']\n",
    "print('------删除之前------')\n",
    "for tempName in movieName:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------删除之后------\n",
      "加勒比海盗\n",
      "骇客帝国\n",
      "霍比特人\n",
      "速度与激情\n"
     ]
    }
   ],
   "source": [
    "# 删除列表中的元素,\n",
    "del movieName[2:4]\n",
    "print('------删除之后------')\n",
    "for tempName in movieName:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------删除之前------\n",
      "加勒比海盗\n",
      "骇客帝国\n",
      "第一滴血\n",
      "指环王\n",
      "霍比特人\n",
      "速度与激情\n",
      "\n",
      "------删除之后------\n",
      "加勒比海盗\n",
      "骇客帝国\n",
      "第一滴血\n",
      "指环王\n",
      "霍比特人\n",
      "\n",
      "pop出来的元素是： 速度与激情\n",
      "['加勒比海盗', '骇客帝国', '第一滴血', '指环王', '霍比特人', '速度与激情']\n"
     ]
    }
   ],
   "source": [
    "# pop  \n",
    "movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']\n",
    "print('------删除之前------')\n",
    "for tempName in movieName:\n",
    "     print(tempName)\n",
    "        \n",
    "x = movieName.pop()  # pop出来的元素可以保存起来\n",
    "print('\\n------删除之后------')\n",
    "for tempName in movieName:\n",
    "    print(tempName)\n",
    "print(\"\\npop出来的元素是：\", x)\n",
    "\n",
    "movieName.append(x)\n",
    "print(movieName)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------删除之前------\n",
      "加勒比海盗\n",
      "骇客帝国\n",
      "第一滴血\n",
      "指环王\n",
      "霍比特人\n",
      "速度与激情\n",
      "\n",
      "------删除之后------\n",
      "加勒比海盗\n",
      "骇客帝国\n",
      "第一滴血\n",
      "霍比特人\n",
      "速度与激情\n"
     ]
    }
   ],
   "source": [
    "# remove \n",
    "movieName = ['加勒比海盗', '骇客帝国', '第一滴血', '指环王', '霍比特人', '速度与激情']\n",
    "print('------删除之前------')\n",
    "for tempName in movieName:\n",
    "    print(tempName)\n",
    "\n",
    "movieName.remove('指环王')\n",
    "print('\\n------删除之后------')\n",
    "for tempName in movieName:\n",
    "    print(tempName)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### （5）列表的排序\n",
    "- **sort**方法：列表的元素按照特定顺序排列。默认由小到大，设置reverse=True由大到小\n",
    "- **reverse**方法：将列表逆置。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "reverse: [3, 2, 4, 1]\n"
     ]
    }
   ],
   "source": [
    "a = [1, 4, 2, 3]\n",
    "a.reverse()    # 逆置，从后往前\n",
    "print(\"reverse:\",a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sort: [1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "a.sort()   # 排序，默认正序\n",
    "print(\"sort:\",a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sort(reverse=True): [4, 3, 2, 1]\n"
     ]
    }
   ],
   "source": [
    "a.sort(reverse=True)\n",
    "print(\"sort(reverse=True):\",a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 2.3, 5.3, 8, 49]\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "'<' not supported between instances of 'str' and 'int'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-46-1c65efef0b72>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;36m49\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'aaaa'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2.3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m5.3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m8\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msort\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'"
     ]
    }
   ],
   "source": [
    "# 如果list里数据类型同时包含数值和str的话，不能排序\n",
    "a = [49,2,2.3,5.3,8]\n",
    "a.sort()\n",
    "print(a)\n",
    "\n",
    "a = [49,'aaaa',2,2.3,5.3,8]\n",
    "a.sort()  # 会报错"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 列表的嵌套\n",
    "- 指的是一个列表的元素又是一个列表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['北京大学', '清华大学', 1]\n",
      "['南开大学', '天津大学', 1, '天津师范大学']\n",
      "['山东大学', '中国海洋大学']\n",
      "['北京大学', '清华大学', 1]\n",
      "北京大学\n",
      "清华大学\n",
      "1\n",
      "['南开大学', '天津大学', 1, '天津师范大学']\n",
      "南开大学\n",
      "天津大学\n",
      "1\n",
      "天津师范大学\n",
      "['山东大学', '中国海洋大学']\n",
      "山东大学\n",
      "中国海洋大学\n"
     ]
    }
   ],
   "source": [
    "schoolNames = [['北京大学','清华大学',1],\n",
    "               ['南开大学','天津大学',1,'天津师范大学'],\n",
    "              ['山东大学','中国海洋大学']\n",
    "              ]\n",
    "for i in schoolNames:   # 第一层 还是列表\n",
    "    print(i)\n",
    "    \n",
    "for i in schoolNames:\n",
    "    print(i)\n",
    "    for ii in i:       # 第二次，才是value\n",
    "        print(ii)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二、元组 () tuple\n",
    "- Python的元组与列表类似，不同之处在于**元组的元素不能修改**。元组使用小括号，列表使用方括号。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "tup1 = ('physics', 'chemistry', 1997, 2000)\n",
    "tup2 = (1, 2, 3, 4, 5 )\n",
    "tup3 = (\"a\", \"b\", \"c\", \"d\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 元组的相关操作\n",
    "#### 1. 访问元组\n",
    "- 元组可以使用**下标索引**来访问元组中的值 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "('hello', 100)\n"
     ]
    }
   ],
   "source": [
    "tuple1=('hello',100,4.5)\n",
    "print(tuple1[0])\n",
    "print(tuple1[0:2])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 元组不允许修改元组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-51-832160b9c38e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mtup2\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m(\u001b[0m\u001b[1;34m'abc'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'xyz'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;31m# 以下修改元组元素操作是非法的。\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mtup1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m100\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "tup1 = (12, 34.56);\n",
    "tup2 = ('abc', 'xyz')\n",
    "# 以下修改元组元素操作是非法的。\n",
    "tup1[0] = 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(12, 34.56, 'abc', 'xyz')\n"
     ]
    }
   ],
   "source": [
    "# 创建一个新的元组\n",
    "tup3 = tup1 + tup2;   # 类似extend\n",
    "print (tup3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 元组的遍历\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "a_turple = (1, 2, 3, 4, 5)\n",
    "for num in a_turple:\n",
    "     print(num)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. 元组的内置函数\n",
    "- len(tuple) 计算元组元素个数 \n",
    "- max(tuple) 返回元组中元素最大值 \n",
    "- min(tuple) 返回元组中元素最小值 \n",
    "- tuple(list) 将列表转为元组 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "len: 3\n",
      "maxsize: 98\n",
      "minsize: 4\n",
      "<class 'tuple'> ('Google', 'Taobao', 'Runoob', 'Baidu')\n"
     ]
    }
   ],
   "source": [
    "tuple1 = ('Google', 'Runoob', 'Taobao')\n",
    "\n",
    "# 计算元组元素个数\n",
    "lensize=len(tuple1)\n",
    "print(\"len:\",lensize)\n",
    "\n",
    "# 返回元组元素最大值和最小值\n",
    "tuple2 = ('5', '4', '8', '98')\n",
    "maxsize=max(tuple2)\n",
    "minsize=min(tuple2)\n",
    "print(\"maxsize:\",maxsize)\n",
    "print(\"minsize:\",minsize)\n",
    "\n",
    "# 将列表转为元组\n",
    "list1= ['Google', 'Taobao', 'Runoob', 'Baidu']\n",
    "tuple3 = tuple(list1)\n",
    "print(type(tuple3), tuple3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 三、字典 {} dict\n",
    "### 字典是一种存储数据的容器，它和列表一样，都可以存储多个数据。每个元素都是由两部分组成的，分别是键key和值value。 K-V对"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "info = {'name':'张三',\n",
    "        'sex':'m', \n",
    "        'address':'北京',\n",
    "        'age':23}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典的常见操作\n",
    "#### 1.根据键访问值\n",
    "- **注意：如果使用的是不存在的键，则程序会报错。**\n",
    "- 如果我们不确定字典中是否存在某个键而又想获取其值时，可以使用**get方法，还可以设置默认值**。 \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "张三\n"
     ]
    }
   ],
   "source": [
    "info = {'name':'张三',\n",
    "        'sex':'m', \n",
    "        'address':'北京',\n",
    "        'age':23}\n",
    "print(info['name'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "北京\n"
     ]
    }
   ],
   "source": [
    "print(info['address'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "# print(info['Age'])  # 会报错 Age不存在\n",
    "\n",
    "age = info.get('Age')\n",
    "print(age)     #‘Age’键不存在，所以age为None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'NoneType'>\n",
      "18\n"
     ]
    }
   ],
   "source": [
    "print(type(age))\n",
    "\n",
    "age = info.get('Age', 18)     # 若info不存在‘Age’，返回默认值18\n",
    "print(age)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 修改字典的元素\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入新的学号12344\n",
      "修改之后 {'name': '班长', 'id': 12344, 'sex': 'f', 'address': '地球亚洲中国北京'}\n"
     ]
    }
   ],
   "source": [
    "info = {'name':'班长', \n",
    "        'id':100, \n",
    "        'sex':'f', \n",
    "        'address':'地球亚洲中国北京'}\n",
    "\n",
    "newId = input('请输入新的学号')\n",
    "\n",
    "info['id'] = int(newId)   # dict的修改，直接用key\n",
    "print('修改之后',info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 添加字典元素\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入新的学号123444\n",
      "{'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京', 'id': 123444}\n"
     ]
    }
   ],
   "source": [
    "info = {'name':'班长', \n",
    "        'sex':'f', \n",
    "        'address':'地球亚洲中国北京'}\n",
    "\n",
    "newId = input('请输入新的学号')   \n",
    "info['id'] = int(newId)     # 默认是尾部添加，\n",
    "print(info) \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. 删除字典元素\n",
    "- del：用于删除字典；删除后，字典完全不存在了，无法再根据键访问字典的值。\n",
    "- clear：只是清空字典中的数据，字典还存在，只不过没有元素。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "删除前,{'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}\n",
      "删除后,{'sex': 'f', 'address': '地球亚洲中国北京'}\n"
     ]
    }
   ],
   "source": [
    "# del 删除对应的K_V对，如果只是想清楚value，可以用修改为 ‘’\n",
    "info = {'name':'班长', \n",
    "        'sex':'f', \n",
    "        'address':'地球亚洲中国北京'}\n",
    "\n",
    "print('删除前,%s'%info)\n",
    "\n",
    "del info['name']   \n",
    "print('删除后,%s'%info)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "清空前,{'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}\n",
      "清空后,{}\n"
     ]
    }
   ],
   "source": [
    "# clear\n",
    "info = {'name':'班长', \n",
    "        'sex':'f', \n",
    "        'address':'地球亚洲中国北京'}\n",
    "\n",
    "print('清空前,%s' % info)\n",
    "\n",
    "info.clear()\n",
    "print('清空后,%s' % info)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 5. 计算字典中键值对的个数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7}   # KV对的数量\n",
    "print(len (dict))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 6. 获取字典中键的列表\n",
    "- keys()方法返回在字典中的所有可用的键的列表。 \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['Name', 'Age'])\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7};\n",
    "print(dict.keys())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 7. 获取字典中值的列表\n",
    "- values()方法返回在字典中的所有可用的值的列表 \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_values(['Zara', 7])\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7};\n",
    "print(dict.values())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 8. 获取字典中键值对的列表\n",
    "- items()方法返回字典的(键，值)元组对的列表 \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_items([('Name', 'Zara'), ('Age', 7)])\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7}\n",
    "print(dict.items())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典的遍历\n",
    "#### 1. 遍历字典的键key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name\n",
      "Age\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7}\n",
    "for key in dict.keys():\n",
    "    print(key)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 遍历字典的值value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Zara\n",
      "7\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7}\n",
    "for value in dict.values():\n",
    "     print(value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 遍历字典的元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Name', 'Zara')\n",
      "('Age', 7)\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7}\n",
    "for item in dict.items():\n",
    "     print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('Name', 'Zara'), ('Age', 7)])"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict.items()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. 遍历字典的键值对"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "key=Name，value=Zara\n",
      "key=Age，value=7\n"
     ]
    }
   ],
   "source": [
    "dict = {'Name': 'Zara', 'Age': 7}\n",
    "\n",
    "for key,value in dict.items():\n",
    "    print(\"key=%s，value=%s\"%(key,value))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 课堂练习：给10位老师随机分配到三个办公室中，输出每个办公室的人数和老师姓名。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "办公室1的人数为:2\n",
      "C G \n",
      "\n",
      "办公室2的人数为:5\n",
      "A D E H I \n",
      "\n",
      "办公室3的人数为:3\n",
      "B F J \n",
      "\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "random.randint(0,2)\n",
    "\n",
    "# 定义一个列表用来存储8位老师的名字\n",
    "names = ['A','B','C','D','E','F','G','H','I','J']\n",
    "\n",
    "# 定义一个列表用来保存3个办公室\n",
    "offices = [[],[],[]]\n",
    "\n",
    "for teacher in names:\n",
    "    #print(\"老师姓名：\",teacher)\n",
    "    office_index = random.randint(0,2)  # 生成办公室号 0，1，2\n",
    "    #print(\"抽到的办公室序号：\",office_index)\n",
    "    offices[office_index].append(teacher)   # 放入指定的办公室\n",
    "    #print(\"办公室\", office_index,\"当前人数：\",offices[office_index])\n",
    "    #print()\n",
    "\n",
    "i = 0\n",
    "for office in offices:\n",
    "    print('办公室%d的人数为:%d'%(i+1, len(office)))\n",
    "    for name in office:\n",
    "        print(\"%s\"%name,end = ' ')\n",
    "    print('\\n')\n",
    "    i+=1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "312.997px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "144.5px",
    "left": "886px",
    "right": "20px",
    "top": "95px",
    "width": "350px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
